<?php

namespace app\modules\admin\services;

use app\common\services\BaseService;
use app\models\Advert;
use app\modules\admin\forms\advert\AdvertForm;

class AdvertService extends BaseService{

    /**
     * 搜索
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function search(){
        return Advert::find()->orderBy(['sort'=>SORT_ASC])->all();
    }

    /**
     * 创建
     * @param AdvertForm $form
     * @return bool
     * @throws \Throwable
     */
    public static function create(AdvertForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = new Advert();
        $model->setAttributes($form->getAttributes(),false);
        return $model->insert() !== false;
    }

    /**
     * 更新
     * @param AdvertForm $form
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function update(AdvertForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = Advert::findOne($form->advert_id);
        if(!$model){
            self::setError(\Yii::t("app","广告不存在"));
            return false;
        }
        $model->setAttributes($form->getAttributes(),false);
        return $model->update() !== false;
    }

    /**
     * 获取信息
     * @param $id
     * @return null|static
     */
    public static function getInfoById($id){
        return Advert::findOne($id);
    }

    /**
     * 删除
     * @param $id
     */
    public static function delete($id){
        Advert::deleteAll(['advert_id'=>$id]);
    }
}